import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import '../../controller/auth_controller.dart';
import '../../controller/home_controller.dart';
import '../../controller/admob_controller.dart';
import '../../controller/contract_controller.dart';
import '../../controller/wallet_controller.dart';
import '../../routes/app_routes.dart';
import '../../widgets/custom_app_bar.dart';
import '../../widgets/mining_plans_bottom_sheet.dart';
import '../../widgets/wallet_bottom_sheet.dart';
import 'package:simple_animations/simple_animations.dart';
import 'user_drawer.dart';

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with
        AutomaticKeepAliveClientMixin,
        TickerProviderStateMixin,
        WidgetsBindingObserver {
  final AuthController authController = Get.find();
  final HomeController homeController = Get.find();
  final ContractController contractController = Get.find();
  final AdMobController adMobController = Get.find();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  late VideoPlayerController _videoController;
  bool _isVideoInitialized = false;

  // 淡入控制，避免纹理重建时黑屏闪烁
  late final AnimationController _fadeController;
  late final Animation<double> _fadeAnim;

  @override
  bool get wantKeepAlive => false; // 与原逻辑一致

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    _fadeController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 220),
    );
    _fadeAnim =
        CurvedAnimation(parent: _fadeController, curve: Curves.easeInOut);

    _initializeVideoPlayer();
    _loadPageData();
  }

  /// 初始化视频播放器
  void _initializeVideoPlayer() {
    _videoController = VideoPlayerController.asset('assets/main_bg.mp4');

    _videoController.addListener(() {
      // 当初始化完成且非缓冲时，让视频层淡入；缓冲/未就绪时淡出，露出占位层
      if (!mounted) return;
      final isReady = _videoController.value.isInitialized &&
          !_videoController.value.isBuffering;
      if (isReady) {
        if (_fadeController.status != AnimationStatus.forward &&
            _fadeAnim.value < 1.0) {
          _fadeController.forward();
        }
      } else {
        if (_fadeController.status != AnimationStatus.reverse &&
            _fadeAnim.value > 0.0) {
          _fadeController.reverse();
        }
      }
    });

    _videoController.initialize().then((_) {
      if (!mounted) return;
      setState(() => _isVideoInitialized = true);
      _videoController
        ..setLooping(true)
        ..setVolume(0.0)
        ..play(); // 始终保持播放，避免切后台回来重建首帧黑一下
      _fadeController.forward(); // 首次初始化完成后淡入
    }).catchError((error) {
      print('视频初始化失败: $error');
      if (mounted) {
        setState(() => _isVideoInitialized = false);
      }
    });
  }

  /// 在需要时重新初始化视频播放器
  void _reinitializeVideoIfNeeded() {
    print('开始重新初始化视频播放器');

    // 释放旧资源
    if (_videoController != null) {
      _videoController.removeListener(() {});
      _videoController.pause();
      _videoController.dispose();
    }

    // 重新创建并初始化视频控制器
    _videoController = VideoPlayerController.asset('assets/main_bg.mp4');

    // 添加监听器
    _videoController.addListener(() {
      if (!mounted) return;
      final isReady = _videoController.value.isInitialized &&
          !_videoController.value.isBuffering;
      if (isReady) {
        if (_fadeController.status != AnimationStatus.forward &&
            _fadeAnim.value < 1.0) {
          _fadeController.forward();
        }
      } else {
        if (_fadeController.status != AnimationStatus.reverse &&
            _fadeAnim.value > 0.0) {
          _fadeController.reverse();
        }
      }
    });

    // 初始化并播放
    _videoController.initialize().then((_) {
      if (!mounted) return;
      print('视频重新初始化成功');
      setState(() => _isVideoInitialized = true);
      _videoController
        ..setLooping(true)
        ..setVolume(0.0)
        ..play();
      _fadeController.forward();
    }).catchError((error) {
      print('视频重新初始化失败: $error');
      if (mounted) {
        setState(() => _isVideoInitialized = false);
      }
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _fadeController.dispose();
    _videoController.dispose();
    super.dispose();
  }

  /// 检查账户绑定状态
  void _checkBindingStatus() {
    if (!authController.isBindAccount.value) {
      authController.showLoginDialog();
      once(authController.isBindAccount, (isBindAccount) {
        if (isBindAccount == true) {
          homeController.getHomeData();
          _scaffoldKey.currentState?.openDrawer();
        }
      });
    } else {
      _scaffoldKey.currentState?.openDrawer();
    }
  }

   void _checkBindingStatusToWallet() {
    if (!authController.isBindAccount.value) {
      authController.showLoginDialog();
      once(authController.isBindAccount, (isBindAccount) {
        if (isBindAccount == true) {
          homeController.getHomeData();
          WalletBottomSheet.show();
        }
      });
    } else {
     WalletBottomSheet.show();
    }
  }

  /// 应用生命周期状态变化监听
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    print('生命周期状态变化: $state');

    switch (state) {
      case AppLifecycleState.resumed:
        // 从后台恢复时，检查视频控制器状态，必要时重新初始化
        print('应用恢复到前台');

        // 检查视频控制器是否需要重新初始化
        bool needsReinitialize = !_isVideoInitialized ||
            !_videoController.value.isInitialized ||
            _videoController.value.position >=
                _videoController.value.duration -
                    const Duration(milliseconds: 100);

        if (needsReinitialize) {
          print('视频控制器需要重新初始化');
          _reinitializeVideoIfNeeded();
        } else {
          print('视频控制器状态正常，继续播放');
          // 控制器状态正常，确保播放并触发淡入
          if (!_videoController.value.isPlaying) {
            _videoController.play();
          }
          _fadeController.forward();
        }
        break;

      case AppLifecycleState.paused:
        print('应用进入后台');
        break;
      case AppLifecycleState.inactive:
        print('应用处于非活跃状态');
        break;
      case AppLifecycleState.detached:
        print('应用已分离');
        break;
      case AppLifecycleState.hidden:
        print('应用被隐藏');
        break;
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadPageData();
  }

  /// 加载页面数据
  void _loadPageData() {
    // contractController.getUserContractList();
    homeController.getHomeData();
  }

  bool get _showVideoLayer =>
      _isVideoInitialized && _videoController.value.isInitialized;

  @override
  Widget build(BuildContext context) {
    super.build(context); // AutomaticKeepAliveClientMixin 需要
    return Obx(() => Scaffold(
          key: _scaffoldKey,
          backgroundColor: const Color(0xFF1A1A1A), // 深色背景
          drawer: UserDrawer(),
          // 禁用侧滑手势，只有绑定账户后才能通过侧滑打开抽屉
          drawerEnableOpenDragGesture: authController.isBindAccount.value,
          body: Stack(
            children: [
              // =================== 背景视频区域（保持你原来的布局与左右15px） ===================
              if (_showVideoLayer)
                Positioned(
                  left: 15,
                  right: 15,
                  top: 0,
                  bottom: 0,
                  child: Stack(
                    fit: StackFit.expand,
                    children: [
                      // 占位层：使用与视频相同的图片作为底层，避免初始化/缓冲/纹理重建时黑屏
                      Image.asset(
                        'assets/main_bg_image.png',
                        fit: BoxFit.cover, // 与视频相同的填充模式
                        alignment: Alignment.center,
                        width: double.infinity,
                        height: double.infinity,
                      ),

                      // 真正的视频层：用淡入避免黑闪
                      FadeTransition(
                        opacity: _fadeAnim,
                        child: FittedBox(
                          fit: BoxFit.cover, // 覆盖整个区域（你原来的逻辑）
                          alignment: Alignment.center,
                          child: SizedBox(
                            width: _videoController.value.size.width,
                            height: _videoController.value.size.height,
                            child: VideoPlayer(_videoController),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),

              // =================== 主内容 ===================
              Column(
                children: [
                  SafeArea(
                    child: CustomAppBar(
                      onAvatarTap: () {
                        // 异步调用 getHomeData 方法，不阻塞后续执行
                        homeController.getHomeData().catchError((e) {
                          print('头像点击刷新数据出错: $e');
                        });

                        final token = authController.accessToken;
                        if (token.isEmpty) {
                          authController.checkStartupLogin().then((success) {
                            if (success) {
                              _checkBindingStatus();
                            } else {
                              Get.snackbar(
                                'Login Required',
                                'Please login first to access menu',
                                backgroundColor: Colors.red,
                                colorText: Colors.white,
                                snackPosition: SnackPosition.TOP,
                              );
                            }
                          });
                        } else {
                          _checkBindingStatus();
                        }
                      },
                    ),
                  ),
                  Expanded(
                    child: Stack(
                      children: [
                        Align(
                          alignment: const Alignment(0, -0.3),
                          child: Obx(() => PowerValueDisplay(
                                totalPower:
                                    homeController.btcTotalPower.toString(),
                                controller: AnimationController(
                                  vsync: this,
                                  duration: const Duration(milliseconds: 2500),
                                )..repeat(reverse: true),
                                homeController: homeController,
                                onTap: () async {
                                  final authController =
                                      Get.find<AuthController>();
                                  if (!authController.isLoggedIn.value) {
                                    // 如果未登录，调用checkStartupLogin方法
                                    await authController.checkStartupLogin();
                                    if (!authController.isLoggedIn.value) {
                                      return; // 如果登录失败，直接返回
                                    }
                                  }

                                  if (contractController
                                          .contractListData.value ==
                                      null) {
                                    await contractController.getContractList();
                                  }
                                  showModalBottomSheet(
                                    context: context,
                                    backgroundColor: Colors.transparent,
                                    isScrollControlled: true,
                                    builder: (context) =>
                                        MiningPlansBottomSheet(
                                      contractData: contractController
                                          .contractListData.value,
                                      onFreePlanTap: () {
                                        Navigator.pop(context);
                                        final authController =
                                            Get.find<AuthController>();
                                        if (authController.isLoggedIn.value) {
                                          final adMobController =
                                              Get.find<AdMobController>();
                                          adMobController.showRewardedAd(
                                            adUnitId: AdMobController
                                                .FREE_PLAN_AD_UNIT,
                                            onUserEarnedReward:
                                                (ad, reward) async {},
                                          );
                                        } else {
                                          authController.showLoginDialog();
                                        }
                                      },
                                      onRunningPlansTap: () {
                                        Navigator.pop(context);
                                        Get.toNamed('/running-plans');
                                      },
                                      onPurchaseTap: (contract) {},
                                    ),
                                  );
                                },
                              )),
                        ),
                        Positioned(
                          left: MediaQuery.of(context).size.width * 0.05,
                          right: MediaQuery.of(context).size.width * 0.05,
                          bottom: MediaQuery.of(context).size.height * 0.10,
                          child: Container(
                            height: (MediaQuery.of(context).size.height * 0.08)
                                .clamp(60.0, 100.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                // WALLET 按钮
                                Expanded(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      GestureDetector(
                                        onTap: () {
                                          // 异步调用 getHomeData 方法，不阻塞后续执行
                                          homeController
                                              .getHomeData()
                                              .catchError((e) {
                                            print('头像点击刷新数据出错: $e');
                                          });

                                          final token =
                                              authController.accessToken;
                                          if (token.isEmpty) {
                                            authController
                                                .checkStartupLogin()
                                                .then((success) {
                                              if (success) {
                                                _checkBindingStatus();
                                              } else {
                                                Get.snackbar(
                                                  'Login Required',
                                                  'Please login first to access menu',
                                                  backgroundColor: Colors.red,
                                                  colorText: Colors.white,
                                                  snackPosition:
                                                      SnackPosition.TOP,
                                                );
                                              }
                                            });
                                          } else {
                                            _checkBindingStatus();
                                          }
                                        },
                                        child: Container(
                                          height: (MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                  0.06)
                                              .clamp(35.0, 65.0),
                                          decoration: BoxDecoration(
                                            color: Color.fromRGBO(
                                                25, 20, 10, 0.72),
                                            borderRadius: BorderRadius.circular(
                                                ((MediaQuery.of(context)
                                                                .size
                                                                .height *
                                                            0.06)
                                                        .clamp(35.0, 65.0)) /
                                                    2),
                                            boxShadow: [
                                              BoxShadow(
                                                color: Colors.black
                                                    .withOpacity(0.15),
                                                blurRadius: 4,
                                                offset: Offset(0, 2),
                                              ),
                                            ],
                                          ),
                                          child: Center(
                                            child: Text(
                                              'PROFILE',
                                              style: TextStyle(
                                                color: Color(0xFFFFB000),
                                                fontSize:
                                                    (MediaQuery.of(context)
                                                                .size
                                                                .width *
                                                            0.03)
                                                        .clamp(10.0, 16.0),
                                                fontWeight: FontWeight.bold,
                                                letterSpacing: 1,
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                      Transform.translate(
                                        offset: Offset(0, -5),
                                        child: Text(
                                          'VIEW DETIALS',
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: (MediaQuery.of(context)
                                                        .size
                                                        .width *
                                                    0.022)
                                                .clamp(7.0, 11.0),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),

                                SizedBox(
                                    width: (MediaQuery.of(context).size.width *
                                            0.04)
                                        .clamp(10.0, 20.0)),

                                // MANAGE PLANS 按钮 (中间，保持发光效果)
                                Expanded(
                                  flex: 2,
                                  child: Obx(() => ManagePlansButton(
                                        onTap: () async {
                                          final authController =
                                              Get.find<AuthController>();
                                          if (!authController
                                              .isLoggedIn.value) {
                                            // 如果未登录，调用checkStartupLogin方法
                                            await authController
                                                .checkStartupLogin();
                                            if (!authController
                                                .isLoggedIn.value) {
                                              return; // 如果登录失败，直接返回
                                            }
                                          }

                                          if (contractController
                                                  .contractListData.value ==
                                              null) {
                                            await contractController
                                                .getContractList();
                                          }
                                          showModalBottomSheet(
                                            context: context,
                                            backgroundColor: Colors.transparent,
                                            isScrollControlled: true,
                                            builder: (context) =>
                                                MiningPlansBottomSheet(
                                              contractData: contractController
                                                  .contractListData.value,
                                              onFreePlanTap: () {
                                                Navigator.pop(context);
                                                final authController =
                                                    Get.find<AuthController>();
                                                if (authController
                                                    .isLoggedIn.value) {
                                                  final adMobController = Get
                                                      .find<AdMobController>();
                                                  adMobController
                                                      .showRewardedAd(
                                                    adUnitId: AdMobController
                                                        .FREE_PLAN_AD_UNIT,
                                                    onUserEarnedReward:
                                                        (ad, reward) async {},
                                                  );
                                                } else {
                                                  authController
                                                      .showLoginDialog();
                                                }
                                              },
                                              onRunningPlansTap: () {
                                                Navigator.pop(context);
                                                Get.toNamed('/running-plans');
                                              },
                                              onPurchaseTap: (contract) {},
                                            ),
                                          );
                                        },
                                        isLoading: contractController
                                            .isLoadingContracts.value,
                                      )),
                                ),

                                SizedBox(
                                    width: (MediaQuery.of(context).size.width *
                                            0.04)
                                        .clamp(10.0, 20.0)),

                                // WATCH AD 按钮
                                Expanded(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      GestureDetector(
                                        onTap: () {
                                          // 观看广告逻辑
                                          // final authController = Get.find<AuthController>();
                                          // if (authController.isLoggedIn.value) {
                                          //   // final adMobController = Get.find<AdMobController>();
                                          //   // adMobController.showRewardedAd(
                                          //   //   adUnitId: AdMobController.FREE_PLAN_AD_UNIT,
                                          //   //   onUserEarnedReward: (ad, reward) async {
                                          //   //     print('User earned reward: ${reward.amount} ${reward.type}');
                                          //   //     // 可以在这里添加奖励逻辑
                                          //   //   },
                                          //   // );
                                          //   // Get.toNamed('/running-plans');
                                          //    WalletBottomSheet.show();
                                          // } else {
                                          //   authController.showLoginDialog();
                                          // }
                                          final token =
                                              authController.accessToken;
                                          if (token.isEmpty) {
                                            authController
                                                .checkStartupLogin()
                                                .then((success) {
                                              if (success) {
                                                _checkBindingStatusToWallet();
                                              } else {
                                                Get.snackbar(
                                                  'Login Required',
                                                  'Please login first to access menu',
                                                  backgroundColor: Colors.red,
                                                  colorText: Colors.white,
                                                  snackPosition:
                                                      SnackPosition.TOP,
                                                );
                                              }
                                            });
                                          } else {
                                            _checkBindingStatusToWallet();
                                          }
                                        },
                                        child: Container(
                                          height: (MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                  0.06)
                                              .clamp(35.0, 65.0),
                                          decoration: BoxDecoration(
                                            color: Color.fromRGBO(
                                                25, 20, 10, 0.72),
                                            borderRadius: BorderRadius.circular(
                                                ((MediaQuery.of(context)
                                                                .size
                                                                .height *
                                                            0.06)
                                                        .clamp(35.0, 65.0)) /
                                                    2),
                                            boxShadow: [
                                              BoxShadow(
                                                color: Colors.black
                                                    .withOpacity(0.15),
                                                blurRadius: 4,
                                                offset: Offset(0, 2),
                                              ),
                                            ],
                                          ),
                                          child: Center(
                                            child: Text(
                                              'WALLET',
                                              style: TextStyle(
                                                color: Color(0xFFFFB000),
                                                fontSize:
                                                    (MediaQuery.of(context)
                                                                .size
                                                                .width *
                                                            0.03)
                                                        .clamp(10.0, 16.0),
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                      Transform.translate(
                                        offset: Offset(0, -5),
                                        child: Text(
                                          'VIEW BALANCE',
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: (MediaQuery.of(context)
                                                        .size
                                                        .width *
                                                    0.022)
                                                .clamp(7.0, 11.0),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),

                        // 云挖矿免责声明
                        Positioned(
                          left: 20,
                          right: 20,
                          bottom: MediaQuery.of(context).size.height * 0.01,
                          child: Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 12, vertical: 8),
                            decoration: BoxDecoration(
                              color: Colors.black.withOpacity(0.3),
                              borderRadius: BorderRadius.circular(8),
                              border: Border.all(
                                color: Colors.white.withOpacity(0.1),
                                width: 1,
                              ),
                            ),
                            child: Text(
                              'remote_mining_notice'.tr,
                              textAlign: TextAlign.center,
                              maxLines: 3,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: Colors.white.withOpacity(0.7),
                                fontSize: 10,
                                height: 1.2,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ));
  }
}

// 能量值显示
class PowerValueDisplay extends StatefulWidget {
  final String totalPower;
  final AnimationController controller;
  final HomeController homeController;
  final Future<void> Function()? onTap;

  const PowerValueDisplay({
    Key? key,
    required this.totalPower,
    required this.controller,
    required this.homeController,
    this.onTap,
  }) : super(key: key);

  @override
  State<PowerValueDisplay> createState() => _PowerValueDisplayState();
}

class _PowerValueDisplayState extends State<PowerValueDisplay> {
  bool _isProcessing = false;

  Future<void> _handleTap() async {
    if (_isProcessing || widget.onTap == null) return;

    setState(() {
      _isProcessing = true;
    });

    try {
      await widget.onTap!();
    } finally {
      if (mounted) {
        setState(() {
          _isProcessing = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: AnimatedBuilder(
        animation: widget.controller,
        builder: (context, child) {
          final scale = 1.0 + widget.controller.value * 0.05; // 1.0 到 1.05 的缩放
          return Transform.scale(
            scale: scale,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  'TOTAL POWER',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white.withOpacity(0.7),
                    letterSpacing: 1.5,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 10),
                // 算力值显示
                Text(
                  widget.totalPower,
                  style: TextStyle(
                    fontSize: 60,
                    fontWeight: FontWeight.bold,
                    color: Color.lerp(
                      const Color(0xFFFFD700), // 金黄色
                      const Color(0xFFFFF176), // 亮黄色
                      widget.controller.value,
                    ),
                    shadows: [
                      Shadow(
                        color: const Color(0xFFFFD700)
                            .withOpacity(0.5 + widget.controller.value * 0.3),
                        blurRadius: 15 + widget.controller.value * 10,
                        offset: const Offset(0, 0),
                      ),
                    ],
                  ),
                ),
                // 单位显示
                Text(
                  'Gh/s',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w600,
                    color: Color.lerp(
                      const Color(0xFFFFD700), // 金黄色
                      const Color(0xFFFFF176), // 亮黄色
                      widget.controller.value,
                    ),
                    letterSpacing: 1.2,
                  ),
                ),
                // 免费算力时间显示
                Obx(() {
                  final freePowerTime = widget.homeController.freePowerTime;
                  if (freePowerTime > 0) {
                    return Padding(
                      padding: const EdgeInsets.only(top: 4),
                      child: Text(
                        'For ${freePowerTime % 1 == 0 ? freePowerTime.toInt().toString() : freePowerTime.toStringAsFixed(1)}h',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: Color.lerp(
                            const Color(0xFFFFD700), // 金黄色
                            const Color(0xFFFFF176), // 亮黄色
                            widget.controller.value,
                          ),
                          letterSpacing: 1.0,
                        ),
                      ),
                    );
                  }
                  return const SizedBox.shrink();
                }),
              ],
            ),
          );
        },
      ),
    );
  }
}

// 管理计划按钮
class ManagePlansButton extends StatefulWidget {
  final Future<void> Function() onTap;
  final bool isLoading;

  const ManagePlansButton({
    Key? key,
    required this.onTap,
    this.isLoading = false,
  }) : super(key: key);

  @override
  _ManagePlansButtonState createState() => _ManagePlansButtonState();
}

class _ManagePlansButtonState extends State<ManagePlansButton>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  bool _isPressed = false;
  bool _isProcessing = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    )..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Future<void> _handleTap() async {
    if (_isProcessing || widget.isLoading) return;

    setState(() {
      _isProcessing = true;
      _isPressed = false;
    });

    try {
      await widget.onTap();
    } finally {
      if (mounted) {
        setState(() {
          _isProcessing = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;
    final buttonWidth = (screenWidth * 0.5).clamp(180.0, 260.0);
    final buttonHeight = (screenHeight * 0.06).clamp(48.0, 64.0);
    final labelFontSize = (screenWidth * 0.04).clamp(12.0, 18.0);

    return GestureDetector(
      onTapDown: (_isProcessing || widget.isLoading)
          ? null
          : (_) => setState(() => _isPressed = true),
      onTapUp: (_isProcessing || widget.isLoading)
          ? null
          : (_) {
              setState(() => _isPressed = false);
              _handleTap();
            },
      onTapCancel: (_isProcessing || widget.isLoading)
          ? null
          : () => setState(() => _isPressed = false),
      child: AnimatedBuilder(
        animation: _controller,
        builder: (context, child) {
          return SizedBox(
            width: buttonWidth,
            height: buttonHeight,
            child: CustomPaint(
              painter: GlowingButtonPainter(
                animationValue: _controller.value,
                isPressed: _isPressed,
              ),
              child: Center(
                child: widget.isLoading
                    ? const SizedBox(
                        width: 24,
                        height: 24,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor:
                              AlwaysStoppedAnimation<Color>(Colors.black),
                        ),
                      )
                    : FittedBox(
                        fit: BoxFit.scaleDown,
                        child: Text(
                          'MANAGE PLANS',
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: labelFontSize.toDouble(),
                            fontWeight: FontWeight.bold,
                            letterSpacing: 1.5,
                            shadows: const [
                              Shadow(
                                color: Colors.yellowAccent,
                                blurRadius: 5,
                                offset: Offset(0, 0),
                              ),
                            ],
                          ),
                        ),
                      ),
              ),
            ),
          );
        },
      ),
    );
  }
}

// 发光按钮绘制器
class GlowingButtonPainter extends CustomPainter {
  final double animationValue;
  final bool isPressed;

  GlowingButtonPainter({
    required this.animationValue,
    required this.isPressed,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final rect = Rect.fromLTWH(0, 0, size.width, size.height);
    final rrect = RRect.fromRectAndRadius(rect, const Radius.circular(30));

    final breathValue =
        sin(animationValue * 2 * pi * 0.5) * 0.5 + 0.5; // 0.0-1.0

    final backgroundPaint = Paint();

    // 使用渐变色替代纯色
    final gradient = LinearGradient(
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
      colors: [
        const Color(0xFFFFD700), // 金色
        const Color(0xFFFFA500), // 橙色
      ],
      stops: const [0.3, 1.0],
    ).createShader(rect);

    backgroundPaint.shader = gradient;

    // 根据按压状态调整透明度
    if (isPressed) {
      backgroundPaint.color = Colors.white.withOpacity(0.8);
      backgroundPaint.blendMode = BlendMode.modulate;
    }

    canvas.drawRRect(rrect, backgroundPaint);

    final glowPaint = Paint()
      ..color = const Color(0xFFFFD700).withOpacity(0.3 + breathValue * 0.3)
      ..maskFilter = MaskFilter.blur(BlurStyle.normal, 8 + breathValue * 4);

    final glowRRect = RRect.fromRectAndRadius(
      rect.inflate(2 + breathValue * 3),
      Radius.circular(32 + breathValue * 3),
    );
    canvas.drawRRect(glowRRect, glowPaint);

    // 优化光束宽度和位置计算，使动画更平滑
    final sweepWidth = size.width * 0.8;
    // 使用缓动函数使动画更自然
    final easedAnimation = Curves.easeInOut.transform(animationValue);
    final sweepLeft = size.width * 2 * easedAnimation - sweepWidth;

    canvas.save();
    canvas.clipRRect(rrect);

    // 减小垂直偏移，使光束更平滑
    final verticalOffset = size.height * 0.2;

    // 使用贝塞尔曲线创建更平滑的光束路径
    final path = Path();
    path.moveTo(sweepLeft, -verticalOffset);

    // 使用二次贝塞尔曲线使边缘更平滑
    final controlPointX = sweepLeft + sweepWidth * 0.5;
    path.quadraticBezierTo(
        controlPointX, 0, sweepLeft + sweepWidth, verticalOffset);
    path.lineTo(sweepLeft + sweepWidth, size.height + verticalOffset);
    path.quadraticBezierTo(
        controlPointX, size.height, sweepLeft, size.height - verticalOffset);
    path.close();

    // 使用更丰富的渐变色，增加更多中间色值
    final sweepGradient = LinearGradient(
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
      colors: [
        Colors.white.withOpacity(0.0),
        Colors.white.withOpacity(0.2),
        Colors.white.withOpacity(0.6),
        Colors.white.withOpacity(0.2),
        Colors.white.withOpacity(0.0),
      ],
      stops: const [0.0, 0.2, 0.5, 0.8, 1.0],
    );

    final sweepPaint = Paint()
      ..shader = sweepGradient
          .createShader(Rect.fromLTWH(sweepLeft, 0, sweepWidth, size.height));

    canvas.drawPath(path, sweepPaint);
    canvas.restore();
  }

  @override
  bool shouldRepaint(GlowingButtonPainter oldDelegate) {
    return oldDelegate.animationValue != animationValue ||
        oldDelegate.isPressed != isPressed;
  }
}
